package com.axend.aerosense.room.ui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.common.bean.PersonSelectItemBean;
import com.axend.aerosense.common.bean.WardSelectItemBean;
import com.axend.aerosense.room.ui.fragment.RoomPersonSelectFragment;
import com.axend.aerosense.room.ui.fragment.RoomWardSelectFragment;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.viewmodel.BaseViewModel;
import com.axend.aerosense.common.adapter.ScreenAutoAdapter;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomActivityAddRoomBinding;
import com.axend.aerosense.room.entity.RoomItemBean;
import com.axend.aerosense.room.ui.fragment.RoomCreateFragment;
import com.axend.aerosense.room.ui.fragment.RoomPersonSettingFragment;
import com.axend.aerosense.room.ui.fragment.RoomWardSettingFragment;
import com.axend.aerosense.room.ui.fragment.RoomSettingFragment;

/**
 * @author 房间新增设定界面承载主体
 * @date :2020/12/29 14:59
 */
@Route(path = RouterActivityPath.Room.PAGE_ROOM_SETTING)
public class RoomAddActivity extends MvvmBaseActivity<RoomActivityAddRoomBinding, BaseViewModel> {
    public static final int RUQUST_CODE = 1501;
    public static final int RESPONSE_CODE_CLOSE = 1511;
    private RoomItemBean editRoomInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ScreenAutoAdapter.match(this, 375.0f);
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        ImmersionBar.with(this)
                .statusBarColor(android.R.color.white)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
        setSupportActionBar(viewDataBinding.roomToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        editRoomInfo = (RoomItemBean) getIntent().getSerializableExtra(RoomSettingFragment.OPEN_PARAM_ROOMINFO);
        setRightTitle("");
        getSupportFragmentManager().addOnBackStackChangedListener(getListener());
        if (null != editRoomInfo) {
            // 房间设定的编辑模式
            RoomSettingFragment fragment = RoomSettingFragment.getInstance();
            Bundle bundle = new Bundle();
            bundle.putSerializable(RoomSettingFragment.OPEN_PARAM_ROOMINFO, editRoomInfo);
            fragment.setArguments(bundle);
            bindFragment(fragment);

        } else {
            // 创建房间模式
            bindFragment(RoomCreateFragment.getInstance());
        }

    }

    private void bindFragment(Fragment fragment) {
        FragmentUtil.add(this,viewDataBinding.roomContent.getId(),fragment, null, false);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            finish();
            return;
        }
//        FragmentUtils.show(getSupportFragmentManager());
        super.onBackPressed();
    }

    private void init() {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_activity_add_room;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected BaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    public void setTitle(String title) {
        viewDataBinding.roomTitle.setText(title);
    }

    public void setRightTitle(String title) {
        viewDataBinding.roomToolbar.setMySettingText(title);
        if (!TextUtils.isEmpty(title)) {
            viewDataBinding.roomToolbar.setRightTitleVisibility(View.VISIBLE);
        } else {
            viewDataBinding.roomToolbar.setRightTitleVisibility(View.GONE);
        }
    }

//    public void setRightTiteClickLisetence(){
//        viewDataBinding.roomToolbar.setSettingTextOnClickListener(v->{
//            ToastUtils.showShort("current fragment:" + getSupportFragmentManager().findFragmentById(getContentId()).getClass().getSimpleName());
////            ((CityBaseFragment)getSupportFragmentManager().findFragmentById(getContentId())).complete();
//        });
//    }

    private FragmentManager.OnBackStackChangedListener getListener() {
        FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener() {
            public void onBackStackChanged() {
                FragmentManager manager = getSupportFragmentManager();
                if (manager != null) {
                    Fragment currFrag = (Fragment) manager.findFragmentById(getContentId());
                    currFrag.onResume();
                }
            }
        };

        return result;
    }


    public int getContentId() {
        return viewDataBinding.roomContent.getId();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (data == null) {
            return;
        }
        if (requestCode == RoomSettingFragment.REQUEST_PERSON) {
            RoomSettingFragment fragment = (RoomSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomSettingFragment.class.getSimpleName());
            fragment.setPerson((PersonSelectItemBean) data.getSerializableExtra(RoomPersonSelectFragment.SELECT_PERSON));

        } else if (requestCode == RoomSettingFragment.REQUEST_WARD) {
            RoomSettingFragment fragment = (RoomSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomSettingFragment.class.getSimpleName());
            fragment.setWard((WardSelectItemBean) data.getSerializableExtra(RoomWardSelectFragment.SELECT_WARD));

        } else if(requestCode == SaveModelActivity.REQUEST_CODE_SET_TYPE || requestCode == SaveModelActivity.REQUEST_CODE_SET_NAME){
            RoomSettingFragment fragment = (RoomSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomSettingFragment.class.getSimpleName());
            fragment.onActivityResult(requestCode, resultCode, data);

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
